package mani.threads;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class ProducerConsumer {

	public static void main(String[] args) {
		Storage storage = new Storage();
		Producer producer = new Producer(storage);
		Consumer consumer = new Consumer(storage);
		
		Thread prodThread = new Thread(producer);
		Thread consThread = new Thread(consumer);
		prodThread.start();
		consThread.start();
	}

}

class Storage{
	private List<Date> dateList;
	private int maxSize;
	
	Storage(){
		maxSize=10;
		dateList = new LinkedList<Date>();
	}
	
	public synchronized void produce(){
		if(dateList.size()==maxSize){
			try{
				wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}			
		}
		Date d = new Date();
		dateList.add(d);
		System.out.println("Produced---"+d);
		notifyAll();
		
	}
	
	public synchronized void consume(){
		if(dateList.size()==0){
			try{
				wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		int index = dateList.size()-1;
		Date d = dateList.remove(index);
		System.out.println("Consumed----"+d);
		notifyAll();
	}
}

class Producer implements Runnable{
	private Storage storage;
	
	Producer(Storage storage){
		this.storage = storage;
	}
	public void run(){
		for(int i = 0;i<15;i++){
			storage.produce();
		}
	}
}

class Consumer implements Runnable{
	private Storage storage;
	Consumer(Storage storage){
		this.storage = storage;
	}
	public void run(){
		for(int i = 0;i<15;i++){
			storage.consume();
		}
	}
}
